﻿using Minio;
using Minio.Exceptions;
using System;
using System.Configuration;
using System.Threading.Tasks;

namespace Partner.Surround.MinIO
{
    public class MinIOManager
    {
        private readonly MinioClient MinioClient;
        private readonly Configuration _configuration;

        public MinIOManager(Configuration configuration)
        {
            _configuration = configuration;

            var endpoint = "xxx.xxx.xxx.xxx:9800";
            var accessKey = "你的accesskey";
            var secretKey = "你的secretKey";

            MinioClient = MinIOClientFactory.Create(endpoint, accessKey, secretKey);
        }

        public async Task UploadFile(string objectName, string filePath, string contentType, string bucketName = "default", string location = "us-east-1")
        {
            // 检查是否存在bucket
            bool found = await MinioClient.BucketExistsAsync(bucketName);
            if (!found)
            {
                // 创建bucket
                await MinioClient.MakeBucketAsync(bucketName, location);
            }

            // 上传文件到bucket
            await MinioClient.PutObjectAsync(bucketName, objectName, filePath, contentType);
        }

        public async Task GetBucketListAsync()
        {
            var bucketList = await MinioClient.ListBucketsAsync();
        }

        public void GetFileListAsync(string bucketName)
        {
            var fileList = MinioClient.ListObjectsAsync(bucketName);
        }

        /// <summary>
        /// 获取文件下载/访问Url
        /// </summary>
        /// <param name="bucketName">存储空间名</param>
        /// <param name="objectName">文件名</param>
        /// <param name="expiresInt">有效期秒数，最大7天(604800秒)</param>
        /// <returns></returns>
        public async Task<string> GetFileUrlAsync(string bucketName, string objectName, int expiresInt = 604800)
        {
            var fileUrl = await MinioClient.PresignedGetObjectAsync(bucketName, objectName, expiresInt);
            return fileUrl;
        }
    }
}
